package com.cooge.jiexi;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class SQLUtil {

	@SuppressWarnings("unused")
	public static void main(String[] args) throws Exception {
		

		File file = new File("ip___"+System.currentTimeMillis()+".txt");
		FileOutputStream  fos = new FileOutputStream(file);
		OutputStreamWriter opw= new OutputStreamWriter(fos,"utf-8");
		PrintWriter pw = new PrintWriter(opw, true);
		Map<String, Integer> map = new HashMap<String, Integer>();
		
		String paths[] = {"C:\\Users\\楚平\\Documents\\Tencent Files\\371984618\\FileRecv\\db_0709.sql"};
		int  i_ = 0;
		for(String path:paths){
			FileInputStream fis = new FileInputStream(new File(path));
			InputStreamReader isr  = new InputStreamReader(fis);
			@SuppressWarnings("resource")
			BufferedReader br = new BufferedReader(isr);
			
			String line = null;
			int i =0;
			while((line=br.readLine())!=null){
				i++;
				String sql = (getSQL(line));
				if(sql!=null&&sql.length()>0){
					System.out.println(sql);
					
					Integer num =  map.get(sql);
					if(num==null){
						map.put(sql, 1);
					}else{
						map.put(sql, num+1);
					}
				}else{
					System.out.println(i);
				}
				
			}
			
		}
		map = Test.sortByValue(map);
		Iterator<Entry<String, Integer>> set = map.entrySet().iterator();
		while(set.hasNext()){
			Entry<String, Integer> ent=  set.next();
				pw.println("sql语句:        "+ent.getKey()+"         次数:"+ent.getValue());
				pw.flush();
		}
		pw.close();
		pw.close();
	
		
		
		
		
		
		
		
		
		
		
		
	}
	
	
	public static String getSQL(String sql){
		try {
			int start = sql.lastIndexOf("','")+3;
			int end  = sql.lastIndexOf("'");
			sql = sql.substring(start, end);
			sql = sql.replaceAll(">", "=").replaceAll("<", "=").replaceAll("= ", "=").replaceAll("=\\d+", "=?").replaceAll(">\\d+", "=?").replaceAll("<\\d+", "=?").replaceAll(",\\d+", ",?").replaceAll("\\d+,", "?,").replaceAll("null", "?").replaceAll("\\\\'.+?\\\'","?");
			int end_ = sql.lastIndexOf("limit");
			if(end_>-1){
				sql = sql.substring(0, end_);
			}
			return sql;
		} catch (Exception e) {
		}
		return null;
		
	}

}
